#!/usr/bin/env bash
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e

main_args=()
extra_args=()

ninja_flags=()
ninja_targets=()

after_double_dash=false

parent_dir=$(dirname "$PWD")
current_dir_name=$(basename "$PWD")

for arg in "$@"; do
    if [[ "$arg" == "--" ]]; then
        after_double_dash=true
    elif [[ "$after_double_dash" == true ]]; then
        extra_args+=("$arg")
    else
        main_args+=("$arg")
    fi
done

if [[ ${#extra_args[@]} -gt 0 ]]; then
    for arg in "${extra_args[@]}"; do
        if [[ "$arg" == -* ]]; then
            ninja_flags+=("$arg")
        else
            ninja_targets+=("$arg")
        fi
    done
fi

if [[ "${main_args[@]}" == *"save_source_files_for_each_target"* ]]; then
    for target in "${ninja_targets[@]}"; do
        file_name="$PWD/component_${target}_component_cpp_files.txt"
        ninja -t commands ${target} | grep 'c++.*\.cpp' | awk '{print $NF}' > ${file_name}
        sed -i "s|${parent_dir}||g" ${file_name}
        sed -i "s|${current_dir_name}/||g" ${file_name}
        sed -i "\|third_party/|d" ${file_name}
    done
fi

set -x
ninja ${extra_args[@]}
